package metadata;

import java.util.*;

import utility.HashBucket;
public class ForeignKey {
	
	//private vars
	private String name						= "";
	private Map<Integer, Column> columns	= null;
	private Key toKey						= null;
	
	private HashBucket index				= null;
	
	//constructors
	public ForeignKey(String name, Key toKey) {
		this.name 	= name;
		this.toKey 	= toKey;
		
		columns 	= new HashMap<Integer, Column>();
	}
	
	
	//util methods
	private List<String> getValuesAt(int index) {
		List<String> dataValues = new ArrayList<String>();
		for(int j = 0; j < columns.size(); ++j) {
			dataValues.add(columns.get(j).getValue(index));
		}
		return dataValues;
	}
	
	//simple getters
	public String getName() 		{ return name; 	}
	public Key getToKey() 			{ return toKey;	}
	public HashBucket getIndex() 	{ return index; }
	
	//simple setters
	public void setName(String name) 	{ this.name 	= name;		}
	public void setToKey(Key toKey)		{ this.toKey 	= toKey;	}

	
	//complex getters
	public Set<Column> getColumnsUnordered() {
		return new HashSet<Column>(columns.values());
	}
	
	
	public Column[] getColumnsOrdered() {
		Column[] columnArray = new Column[columns.size()];
		
		for(int i = 0; i < columns.size(); ++i) {
			columnArray[i] = columns.get(i);
		}
		
		return columnArray;
	}
	
	//complext setters
	
	public void setColumnAt(Column column, Integer index) {
		columns.put(index, column);
	}
	
	//DML
	public void init() {
		index = toKey.getIndex();
	}
	
//	public void init(int rowCount) {
//		
//		indexAtFor(0, rowCount);
//	}
//	
//	public void indexAt(int indexPos) {
//		indexAtFor(indexPos, 1);
//	}
	
	public void indexAtFor(int indexStart, int amount) {
		int indexStop = (indexStart + amount);
		for(int indexPos = indexStart; indexPos < indexStop; ++indexPos) {
			index.addForeignIndexEntry(getValuesAt(indexPos), name, indexPos);
		}
	}
	
	public void removeIndexAt(int indexPos) {
		index.removeForeignIndexEntry(getValuesAt(indexPos), name, indexPos);
	}
	
	public void removeSelfFromIndex() {
		index.removeForeignIndex(name);
	}
}
